package pub.cleangao.mybatis.springboot;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import pub.cleangao.mybatis.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@AutoConfiguration
@ConditionalOnClass(SqlSessionFactory.class)
@AutoConfigureAfter(SqlSessionFactory.class)
public class MyBatisAutoConfiguration implements InitializingBean, ApplicationContextAware {


    private ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, SqlSessionFactory> map = applicationContext.getBeansOfType(SqlSessionFactory.class);
        if (map != null && !map.isEmpty()) {
            List<SqlSessionFactory> sqlSessionFactoryList = new ArrayList<>(map.values());
            Component.start(sqlSessionFactoryList);
        }
    }




}
